#include "rtc.h"

Byte bcd2dec(Byte i){
	return ((i & 0x0F) + 10*((i>>4) & 0x0F));
}

Byte dec2bcd(Byte i){
	return (i % 10 + (((i/10) %10) << 4));
}

void rtc_valid(){
	int op1=get_pic1(), op2=get_pic2();
	
	set_pic_var(0xFF, 0xFF);
	
	outportb(RTC_ADDR_REG, RTC_STAT_A);
	
	while(inportb(RTC_DATA_REG) & RTC_UIP);
	set_pic_var(op1, op2);
}

Byte read_rtc(Byte add){
	int op1=get_pic1(), op2=get_pic2();
	
	set_pic_var(0xFF, 0xFF);
	
	outportb(RTC_ADDR_REG, add);
	Byte valido = inportb(RTC_DATA_REG);

	set_pic_var(op1, op2);
	
	return valido;
}

Byte read_rtcv(Byte add){
	rtc_valid();
	return read_rtc(add);
}

void write_rtc(Byte add, Byte value){
	int op1=get_pic1(), op2=get_pic2();
	
	set_pic_var(0xFF, 0xFF);
	
	outportb(RTC_ADDR_REG, add);
	outportb(RTC_DATA_REG, value);

	set_pic_var(op1, op2);
}

void write_rtcv(Byte add, Byte value){
	rtc_valid();
	write_rtc(add, value);
}

void rtc_read_time(RTC_TIME * rt){

	rt->hour = bcd2dec(read_rtcv(HOUR));
	rt->min = bcd2dec(read_rtcv(MIN));
	rt->sec = bcd2dec(read_rtcv(SEC));
}

void rtc_read_date(RTC_DATE * rd){
	rd->year = bcd2dec(read_rtcv(YEAR));
	rd->month = bcd2dec(read_rtcv(MONTH));
	rd->day = bcd2dec(read_rtcv(MONTH_DAY));
}

void rtc_read_alarm(RTC_TIME * ra){
	ra->hour = bcd2dec(read_rtcv(HOUR_ALARM));
	ra->min = bcd2dec(read_rtcv(MIN_ALARM));
	ra->sec = bcd2dec(read_rtcv(SEC_ALARM));
}

void rtc_write_alarm(RTC_TIME * wa){
	write_rtcv(HOUR_ALARM, dec2bcd(wa->hour));
	write_rtcv(MIN_ALARM, dec2bcd(wa->min));
	write_rtcv(SEC_ALARM, dec2bcd(wa->sec));
}


	
